/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.config;


import com.comac.ins.vo.req.CurrentUserReqVO;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Field;
import java.util.Enumeration;

/**
 * @ClassName: FeignConfiguration
 * @Description: feign处理请求header丢失配置类，未注入spring中，在feignclient中单独指定，例如：
 * @FeignClient(value = "usercenter-service", contextId = "user",configuration = FeignConfiguration.class)
 * @Author: wugongzi
 * @Date: 2021/12/23 15:45
 * @Version: 1.0
 */
@Slf4j
public class FeignConfiguration implements RequestInterceptor {

    @Value("${feign.ssoTenantCode:defaultTenantCode}")
    private String ssoTenantCode;
    @Value("${feign.ssoTenantAccessKey:defaultTenantAccessKey}")
    private String ssoTenantAccessKey;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //设置访问信息
        requestTemplate.header("ssoTenantCode", ssoTenantCode);
        requestTemplate.header("ssoTenantAccessKey", ssoTenantAccessKey);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (null != request && null != headerNames) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String value = request.getHeader(name);
                    // CurrentUserReqVO类为当前登录用户标志类，只注入当前登录用户字段对应的header,其他header像content-length，Accept-Encoding这两个目前注入会报错
                    Field[] fields = CurrentUserReqVO.class.getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        if (name.equals(field.getName())) {
                            requestTemplate.header(name, value);
                        }
                    }
                }
            }
        }
    }
}
